package com.hs.dnms.action.data;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.hs.auth.AUTHConstant;
import com.hs.auth.model.HsAccount;
import com.hs.core.action.BaseAction;
import com.hs.core.cache.GlobalParamCache;
import com.hs.core.db.DBMgr;
import com.hs.core.db.QueryPage;
import com.hs.core.utils.PageParam;
import com.hs.core.utils.PageUtil;
import com.hs.core.utils.PropertiesUtil;
import com.hs.core.utils.SystemUtil;
import com.hs.core.utils.TimeUtil;
import com.hs.core.utils.Tools;
import com.hs.core.utils.UUIDGenerator;
import com.hs.core.utils.UploadfileUtil;
import com.hs.core.utils.ZipfileUtil;
import com.hs.dnms.model.DnmsBook;
import com.hs.dnms.model.DnmsFile;
import com.hs.dnms.service.IDnmsBookService;
@Controller  
public class DataController  extends BaseAction {
    /**
	 * 
	 */
	private static final long serialVersionUID = -354434172898440670L;
	private static final Logger logger = Logger.getLogger(DataController.class);
	private IDnmsBookService bookService;
	@Autowired  
	public void setRoleService(IDnmsBookService magazineService) {
		this.bookService = magazineService;
	}
	 /**
	  * 数据管理框架
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/dataframe.do", method = RequestMethod.GET)   
    public ModelAndView dataframe(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
        
		 return new ModelAndView("app/data/dataframe",modelMap);
		 
	 } 
	 /**
	  * 数据管理主页
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/dataListFrame.do", method = RequestMethod.GET)   
     public ModelAndView dataListFrame(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		   	
		  return new ModelAndView("app/data/datalistframe",modelMap);
		 
	 }
	 /**
	  * 数据详细信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/magainfo.do")   
     public ModelAndView magainfo(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String pid = request.getParameter("id");
		 System.out.println("题录信息主键：" + pid);
		 //题录信息
		 DnmsBook maga = (DnmsBook)this.bookService.findByID(DnmsBook.class, new Long(pid));
		 modelMap.put("obj", maga);
		 return new ModelAndView("app/data/magainfo",modelMap);
		 
	 }
	 
	 
	 /**
	  * 数据管理列表
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/dataList.do")   
     public ModelAndView dataList(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 PageParam pageParam = new  PageParam(request,"data/dataList.do");
		 PageUtil pageUtil = null;
		 String orderName = request.getParameter("orderName");
		 String orderNum = request.getParameter("orderNum");
		 StringBuffer orderByStr = new StringBuffer(" order by ");
		 if(StringUtils.isNotBlank(orderName)){
		    	if("1".equals(orderNum)){
		    		orderByStr.append(orderName).append(" asc");
		    	}
		    	if("2".equals(orderNum)){
		    		orderByStr.append(orderName).append(" desc");
		    	}
		    }else{
		    	orderByStr.append("a.state").append(" desc");
		    	orderName = "a.state";
		    	orderNum = "2";
		    }
		 request.setAttribute("orderName", orderName); 
		 request.setAttribute("orderNum", orderNum); 
		 pageParam.getConditionMap().put("orderName", orderName);
		 pageParam.getConditionMap().put("orderNum", orderNum);
		 StringBuffer searchBuffer = new StringBuffer(" select a from DnmsBook a where 1=1  ");
			String state = request.getParameter("state");  
			String bookname = request.getParameter("bookname");  
			String publishhouse = request.getParameter("publishhouse"); 
			request.setAttribute("state", state);
			request.setAttribute("bookname", bookname);
			request.setAttribute("publishhouse", publishhouse);
			if(StringUtils.isNotBlank(bookname)){
				searchBuffer.append(" and (a.bookname like '%").append(bookname).append("%') ");
				pageParam.getConditionMap().put("bookname", bookname);
				request.setAttribute("bookname", bookname);
			}  
			if(StringUtils.isNotBlank(publishhouse)){
				pageParam.getConditionMap().put("publishhouse", publishhouse);
				searchBuffer.append(" and (a.publishhouse like '%"+publishhouse+"%') "); 
			}
			searchBuffer.append(orderByStr);
			Map data = new HashMap();
			pageParam.setSearchSql(searchBuffer.toString());
			pageUtil = bookService.getList(pageParam);
 			data.put("dataList", pageUtil);     
		 return new ModelAndView("app/data/dataList",data);
		 
	 } 
	 /**
	  * 数据管理分配
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/dataDistribute.do", method = RequestMethod.GET)   
     public ModelAndView dataDistribute(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 
		 StringBuffer searchBuffer = new StringBuffer("select a.loginid,b.username from hs_account a,hs_userinfo b ,hs_accrole c "); 
		 searchBuffer.append(" where A.userid=b.id and a.id=c.accid and c.roleid=2");
		 List producerList = DBMgr.getDbUtilInst().queryList(searchBuffer.toString(),null);
		 Map data = new HashMap();
		 data.put("producerlist", producerList);
		 return new ModelAndView("app/data/datadistribute",data);
	 } 
	 /**
	  * 数据导入主页
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/dataImport.do", method = RequestMethod.GET)   
     public ModelAndView dataImport(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         
		 return new ModelAndView("app/data/dataimport",modelMap);
		 
	 } 
	 /**
	  * 数据导入
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	 * @throws Exception 
	  */
	 @RequestMapping(value="/data/import.do")   
     public ModelAndView importdata(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws Exception {
		 String filepath = SystemUtil.getClassLoaderRoot().getAbsolutePath();
		 PropertiesUtil util = new PropertiesUtil(filepath+"/global_config.properties");
		 String tempFilepath = util.getValue("tempfilepath");
		 System.out.println("开始上传文件。。。。。。。" + tempFilepath);
		 UploadfileUtil uploadfileUtil = new UploadfileUtil();
		 File destfile =  uploadfileUtil.uploadFile(request, tempFilepath);
		 response.getWriter().write("1");
	     //this.readXls(destfile);
		 return new ModelAndView("app/data/dataList",modelMap);
	 } 
	 /**
	  * 数据导入
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	 * @throws Exception 
	  */
	 @RequestMapping(value="/data/importdata.do")   
     public ModelAndView importXlsData(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws Exception {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
		 MultipartFile multipartFile = multipartRequest.getFile("importfile");   
		 String fileName = multipartFile.getOriginalFilename(); 
		// String webRoot = SystemUtil.getWebappRoot().toString();
		 //webRoot = webRoot.replace("\\", "/") + "/temp";
		 String webRoot = GlobalParamCache.getInst().getParamByKey("dnmsabfile");
		 System.out.println("webRoot::" + webRoot );
		 String sep = System.getProperty("file.separator");
		 sep = "/"; 
		 File rootDir = new File(webRoot); 
		 if (!rootDir.exists()) {
			rootDir.mkdirs(); 
		 }
		 String fromfile = webRoot + sep + fileName;
		 String fileSaveUUID = UUIDGenerator.getUUID();
		 String middlePath = Tools.buildFileSubdirectory();
		 String outputfilepath = webRoot + middlePath + sep + fileSaveUUID +  sep ;
		 String savefilepath = middlePath + sep + fileSaveUUID +  sep ;
		 File file = new File(webRoot + sep + fileName);
		 BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(file));
		 bf.write(multipartFile.getBytes());
		 bf.close();
		 
		 System.out.println("上传成功。。。。。。");
		 ZipfileUtil zipfileUtil = new ZipfileUtil();
		 zipfileUtil.unzip(fromfile, outputfilepath);
		 HsAccount accInfo = (HsAccount)request.getSession().getAttribute(AUTHConstant.USERINSESSION);
		 String accid = String.valueOf(accInfo.getId());
		 this.readXls(outputfilepath,savefilepath,accid);
	     response.getWriter().write("1");
		 return new ModelAndView("app/data/dataList",modelMap);
	 }
	 /**
	  * 数据修改
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/saveData.do", method = RequestMethod.GET)   
     public ModelAndView saveData(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         
		 return new ModelAndView("app/data/dataList",modelMap);
		 
	 } 
	 /**
	  * 数据删除
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/dataDelete.do", method = RequestMethod.GET)   
     public ModelAndView dataDelete(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         
		 return new ModelAndView("app/data/dataList",modelMap);
		 
	 } 
	 /**
	  * 读取压缩包
	  * @param zipfile
	  */
	 public void readZipFile(String zipfile){
//		ZipInputStream in = null ;
//		try {
//			in = new ZipInputStream(new FileInputStream(zipfile));
//			ZipEntry z;
//			List bookList = null ;
//			while( ( z = in.getNextEntry() ) != null )
//			{
//				if( !z.isDirectory() )
//				{
//					if( "古籍数据.xls".equals( z.getName() ) )
//					{
//						bookList = this.readXls(in);
//						break;
//					}
//				}
//			}
//			if(bookList != null){
//				for(int i=0; i<bookList.size();i++){
//					DnmsBook dnmsbook = (DnmsBook)bookList.get(i);
//					
//				}
//			}
//			
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	 }
	 
	 /**
	  * 读取excel文件
	  * @param file 要读取的excel文件
	  */
	 public List readXls(String outputfilepath,String savefilepath,String accid){
         List<DnmsBook> bookList = new ArrayList<DnmsBook>();
			HSSFWorkbook workbook = null;
			try {
				File outputFile = new File(outputfilepath + "古籍数据.xls");
				FileInputStream rs = new FileInputStream(outputFile) ;      
				workbook = new HSSFWorkbook(rs);
				int total = workbook.getNumberOfSheets(); //获取sheet个数      
		        int start = 0;
		        int end = 0 ;  
				for(int i = 0 ; i < total ; i ++){  
		            HSSFSheet sheet = workbook.getSheetAt(i);// 按索引获取sheet引用          
		            System.out.println(sheet.getSheetName());      
		            start = sheet.getFirstRowNum();  //sheet起始行索引      
		            end = sheet.getLastRowNum();//sheet起结束行索引      
		            int temp = 1;      
		            HSSFRow row = null ;   
		            HSSFCell itemno = null ;  
		            HSSFCell bookname = null ;      
		            //HSSFCell originalsign = null ; 
		            HSSFCell newsign = null ;
		            HSSFCell diseaseclass = null ; 
		            HSSFCell diseasename = null ; 
		            HSSFCell firstclass = null ; 
		           // HSSFCell secondclass = null ; 
		            HSSFCell originaltext = null ; 
		            HSSFCell lastitem = null ; 
		            HSSFCell nextitem = null ; 
		            HSSFCell chapter = null ; 
		            HSSFCell pagenumber = null ; 
		            HSSFCell enterperson = null ; 
		            HSSFCell enterdate = null ; 
		            HSSFCell author = null ; 
		            HSSFCell compile = null ; 
		            HSSFCell compileunit = null ; 
		            HSSFCell publishhouse = null ;
		            HSSFCell publishplace = null ;
		            HSSFCell publishdate = null ;
		            HSSFCell isbn = null ;
		            HSSFCell edition = null ;
		            HSSFCell wordnumber = null ;
		            HSSFCell booksize = null ;
		            HSSFCell themewords = null ;
		            HSSFCell abstract_ = null ;
		            HSSFCell classcode = null ;
		            HSSFCell dynasty = null ;
		            while(temp <= end){      
		            	 DnmsBook maga = new DnmsBook();
		                 row =  sheet.getRow(temp);//获取第N行表格数据     
		                 if(row != null){
		                	 itemno = row.getCell(0);//获取指定列单元格            
		                	 bookname = row.getCell(1);   
		                	 //originalsign = row.getCell(2);
		                	 newsign = row.getCell(2);
		                	 diseaseclass = row.getCell(3);
		                	 diseasename = row.getCell(4);
		                	 firstclass = row.getCell(5);
		                	 //secondclass = row.getCell(7);
		                	 originaltext = row.getCell(6);
		                	 lastitem = row.getCell(7);
		                	 nextitem = row.getCell(8);
		                	 chapter = row.getCell(9);
		                	 pagenumber = row.getCell(10);
		                	 enterperson = row.getCell(11);
		                	 enterdate = row.getCell(12);
		                	 author = row.getCell(13);
		                	 compile = row.getCell(14);
		                	 compileunit = row.getCell(15);
		                	 publishhouse = row.getCell(16);
		                	 publishplace = row.getCell(17);
		                	 publishdate = row.getCell(18);
		                	 isbn = row.getCell(19);
		                	 edition = row.getCell(20);
		                	 wordnumber = row.getCell(21);
		                	 booksize = row.getCell(22);
		                	 themewords = row.getCell(23);
		                	 abstract_ = row.getCell(24);
		                	 classcode = row.getCell(25);
		                	 dynasty = row.getCell(26);
				                 if(null != itemno){
				                	 maga.setItemno(getCell(itemno)); 
				                 }
				                 if(null != bookname){
				                	 maga.setBookname(getCell(bookname)); 
				                 }
				                 if(null != diseaseclass){
				                	 maga.setDiseaseclass(getCell(diseaseclass)); 
				                 }
				                 if(null != author){
				                	 maga.setAuthor(getCell(author)); 
				                 }
				                 if(null != diseasename){
				                	 maga.setDiseasename(getCell(diseasename)); 
				                 }
				                 if(null != firstclass){
				                	 maga.setFirstclass(getCell(firstclass)); 
				                 }
//				                 if(null != secondclass){
//				                	 maga.setSecondclass(getCell(secondclass)); 
//				                 }
				                 if(null != originaltext){
				                	 maga.setOriginaltext(getCell(originaltext)); 
				                 }
				                 if(null != themewords){
				                	 maga.setThemewords(getCell(themewords)); 
				                 }
				                 if(null != lastitem){
				                	 maga.setLastitem(getCell(lastitem)); 
				                 }
				                 if(null != abstract_){
				                	 maga.setAbstract_(getCell(abstract_)); 
				                 }
				                 if(null != nextitem){
				                	 maga.setNextitem(getCell(nextitem)); 
				                 }
				                 if(null != chapter){
				                	 maga.setChapter(getCell(chapter)); 
				                 }
				                 if(null != pagenumber){
				                	 maga.setPagenumber(getCell(pagenumber)); 
				                 }
				                 if(null != enterperson){
				                	 maga.setEnterperson(getCell(enterperson)); 
				                 }
				                 if(null != enterdate){
				                	 maga.setEnterdate(getCell(enterdate)); 
				                 }
				                 if(null != compile){
				                	 maga.setCompile(getCell(compile)); 
				                 }
				                 if(null != compileunit){
				                	 maga.setCompileunit(getCell(compileunit)); 
				                 }
				                 if(null != publishhouse){
				                	 maga.setPublishhouse(getCell(publishhouse)); 
				                 }
				                 if(null != publishplace){
				                	 maga.setPublishplace(getCell(publishplace)); 
				                 }
				                 if(null != publishdate){
				                	 maga.setPublishdate(getCell(publishdate)); 
				                 }
				                 if(null != isbn){
				                	 maga.setIsbn(getCell(isbn)); 
				                 }
				                 if(null != edition){
				                	 maga.setEdition(getCell(edition)); 
				                 }
				                 if(null != wordnumber){
				                	 maga.setWordnumber(getCell(wordnumber)); 
				                 }
				                 if(null != booksize){
				                	 maga.setBooksize(getCell(booksize)); 
				                 }
				                 if(null != classcode){
				                	 maga.setClasscode(getCell(classcode)); 
				                 }
				                 if(null != dynasty){
				                	 maga.setDynasty(getCell(dynasty)); 
				                 } 				                 
				                 StringBuffer countsql = new StringBuffer();
				                 countsql.append("select id,itemno,pictureproducer,dataproducer,state from dnms_book ");
				                 countsql.append(" where itemno='");
				                 countsql.append(maga.getItemno());
				                 countsql.append("'");
								 List accList = DBMgr.getDbUtilInst().queryList(countsql.toString(),null);  
								 int acclen = accList.size();
							     if(acclen == 0){
							    	 maga.setState("0");
							    	 bookService.saveObject(maga);
							    	 System.out.println("maga.getId()::::" + maga.getId());
							    	 String nsign = getCell(newsign);
								     System.out.println("nsign::::::" + nsign);
								     //String osign = getCell(originalsign);
								     String[] nsignList = nsign.split(";");
								     System.out.println("nsignList::::::" + nsignList.length);
								     //String[] osignList = osign.split(";");
								     for(int j=0; j<nsignList.length; j++){
								    	 DnmsFile dfile = new DnmsFile();
								    	 dfile.setBookid(maga.getId());
								    	 dfile.setFilename(nsignList[j] + ".pdf");
								    	 dfile.setFilepath(savefilepath + getCell(bookname) + "/" + getCell(itemno) + "/" + nsignList[j] + ".pdf");
								    	 //dfile.setOriginalsign(osignList[j]);
								    	 dfile.setNewsign(nsignList[j]);
								    	 dfile.setUploaddate(TimeUtil.getCurrentstr());
								    	 
								    	 dfile.setUserid(Long.parseLong(accid));
								    	 bookService.saveObject(dfile);
								     }
							     }else if(acclen ==1){
							    	 Map data = (Map)accList.get(0);
							    	 String id = data.get("id")+"";
							    	 /*String dataproducer = data.get("dataproducer")+"";
							    	 String pictureproducer = data.get("pictureproducer")+"";
							    	 maga.setState(data.get("state")+"");
							    	 maga.setId(Long.parseLong(id));
							    	 bookService.update(maga);
							    	 String updatesql = "update dnms_book set dataproducer=?,pictureproducer=? where id=?";
							    	 DBMgr.getDbUtilInst().update(updatesql, new Object[]{dataproducer,pictureproducer,id});*/
							    	 StringBuffer usql = new StringBuffer("update dnms_book set ITEMNO=?,BOOKNAME=?,AUTHOR=?,COMPILE=?,COMPILEUNIT=?,PUBLISHHOUSE=?,");
							    	 usql.append("PUBLISHPLACE=?,PUBLISHDATE=?,ISBN=?,EDITION=?,WORDNUMBER=?,BOOKSIZE=?,THEMEWORDS=?,ABSTRACT=?,CLASSCODE=?,FIRSTCLASS=?,");
							    	 usql.append("DISEASECLASS=?,DISEASENAME=?,ORIGINALTEXT=?,LASTITEM=?,NEXTITEM=?,CHAPTER=?,PAGENUMBER=?,ENTERPERSON=?,ENTERDATE=?");
							    	 usql.append("where id=?");
							    	 Object[] obj = new Object[]{maga.getItemno(),maga.getBookname(),maga.getAuthor(),maga.getCompile(),maga.getCompileunit(),maga.getPublishhouse()
							    			 ,maga.getPublishplace(),maga.getPublishdate(),maga.getIsbn(),maga.getEdition(),maga.getWordnumber(),maga.getBooksize(),maga.getThemewords(),
							    			 maga.getAbstract_(),maga.getClasscode(),maga.getFirstclass(),maga.getDiseaseclass(),maga.getDiseasename(),maga.getOriginaltext(),maga.getLastitem(),
							    			 maga.getNextitem(),maga.getChapter(),maga.getPagenumber(),maga.getEnterperson(),maga.getEnterdate(),id};
							    	 DBMgr.getDbUtilInst().update(usql.toString(), obj);
							    	 String nsign = getCell(newsign);
								     String[] nsignList = nsign.split(";");
								     for(int j=0; j<nsignList.length; j++){
								    	 String filepath = savefilepath + getCell(bookname) + "/" + getCell(itemno) + "/" + nsignList[j] + ".pdf";
								    	 String fsql = "update dnms_file set filepath=?,uploaddate=?,userid=? where bookid=? and newsign=?" ;
								    	 DBMgr.getDbUtilInst().update(fsql, new Object[]{filepath,TimeUtil.getCurrentstr(),accid,id,nsignList[j]});
								     }
							     }
		                 }
		                 bookList.add(maga);
		                 temp ++ ; 
		            } 
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
			return bookList;
	}
	public String getCell(HSSFCell cell){
		if(cell==null)return "";
		
		switch(cell.getCellType()){
			case HSSFCell.CELL_TYPE_NUMERIC:
				return (long)cell.getNumericCellValue() + "";
			case HSSFCell.CELL_TYPE_STRING:
				return cell.getStringCellValue();
			case HSSFCell.CELL_TYPE_FORMULA:
				return cell.getCellFormula();
			case HSSFCell.CELL_TYPE_BLANK:
				return "";
			case	HSSFCell.CELL_TYPE_BOOLEAN:
				return cell.getBooleanCellValue() + "";
			case HSSFCell.CELL_TYPE_ERROR:
	    	    return cell.getErrorCellValue() + "";
	    	default:
	    		return "";
		}
	}
	 /**
	  * 数据导出
	  * @param request
	  * @param response
	  * @return
	 * @throws Exception 
	  */
	@RequestMapping("/data/exportData.do")   
	public ModelAndView exportData(HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		try  {
			String path = this.exportData();
			System.out.println("message::" + path );
			//  path是指欲下载的文件的路径。 
			response.setCharacterEncoding("UTF-8");
			File file  =   new  File(path);
			String filename  =  file.getName();
			int fileLength = (int)file.length();
			int length   = 0;
	        ServletOutputStream op       = response.getOutputStream();
	        ServletContext  context  = request.getSession().getServletContext();
	        String mimetype = context.getMimeType( filename );
	        byte[] byteContents   =   new   byte[fileLength];   
	        FileInputStream fis   =   new   FileInputStream(file);   
	        int   retcd   =   fis.read(byteContents);   
	        fis.close();    
	        logger.debug("mimetype:" + mimetype);
	        response.setContentType(mimetype == null?"application/zip":mimetype );
	        response.setContentLength( retcd );
	        response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("gb2312"),"ISO-8859-1") + "\"" );
	        op.write(byteContents,0,retcd); 
	        op.close();
     }  catch  (IOException ex) {
         ex.printStackTrace();
     }
		return null;  
	} 
	/**
	 * 生成题录数据文件
	 * @return 生成的文件的路径
	 */
	public String exportData(){
		String message = "false";
		 try {
				HSSFWorkbook wb = new HSSFWorkbook(); 
				 HSSFSheet sheet = wb.createSheet("new sheet"); 
				 HSSFRow row = sheet.createRow((short)0); 
				 row.createCell(0).setCellValue("条目编码"); 
				 row.createCell(1).setCellValue("书籍名称"); 
				 row.createCell(2).setCellValue("图片现标识"); 
				 row.createCell(3).setCellValue("疾病分类"); 
				 row.createCell(4).setCellValue("古代中医病名"); 
				 row.createCell(5).setCellValue("原文分类"); 
				 row.createCell(6).setCellValue("原文文本化"); 
				 row.createCell(7).setCellValue("上段条目编码"); 
				 row.createCell(8).setCellValue("下段条目编码"); 
				 row.createCell(9).setCellValue("卷册章节"); 
				 row.createCell(10).setCellValue("原文页码"); 
				 row.createCell(11).setCellValue("录入人"); 
				 row.createCell(12).setCellValue("录入日期"); 
				 row.createCell(13).setCellValue("古籍作者"); 
				 row.createCell(14).setCellValue("古籍编辑"); 
				 row.createCell(15).setCellValue("编辑单位"); 
				 row.createCell(16).setCellValue("出版社"); 
				 row.createCell(17).setCellValue("出版地"); 
				 row.createCell(18).setCellValue("出版日期"); 
				 row.createCell(19).setCellValue("标识"); 
				 row.createCell(20).setCellValue("版次、印次"); 
				 row.createCell(21).setCellValue("字数"); 
				 row.createCell(22).setCellValue("开本");
				 row.createCell(23).setCellValue("主题/关键词");
				 row.createCell(24).setCellValue("摘要");
				 row.createCell(25).setCellValue("中图法分类号");
				 row.createCell(26).setCellValue("朝代");
				 CellStyle cs=wb.createCellStyle();  
				 List accList = DBMgr.getDbUtilInst().queryList("select * from dnms_book order by id",null);
				 for(int i=0; i<accList.size(); i++){
						Map data = (Map)accList.get(i);
						HSSFRow onerow = sheet.createRow((short)(i+1)); 
						Object obj  = data.get("id");
						if(obj instanceof Long){
							System.out.println("*****************");
						}else if(obj instanceof Integer){
							System.out.println("&&&&&&&&&&&&&");
						}else if(obj instanceof Double){
							System.out.println("################");
						}
						String id = data.get("id")+"";
						List signList = DBMgr.getDbUtilInst().queryList("select * from dnms_file where bookid=? order by id",new Object[]{id});
						String newsign = "" ;
						for(int j=0; j<signList.size();j++){
							Map onesign = (Map)signList.get(j);
							newsign = newsign + onesign.get("newsign") + ";";
						}
						if(newsign.endsWith(";")) newsign = newsign.substring(0,newsign.length()-1);
						onerow.createCell(0).setCellValue(String.valueOf(data.get("itemno"))); 
						onerow.createCell(1).setCellValue((String)data.get("bookname")); 
						onerow.createCell(2).setCellValue(newsign); 
						onerow.createCell(3).setCellValue((String)data.get("diseaseclass")); 
						onerow.createCell(4).setCellValue((String)data.get("diseasename")); 
						onerow.createCell(5).setCellValue((String)data.get("firstclass")); 
						onerow.createCell(6).setCellValue((String)data.get("originaltext")); 
						onerow.createCell(7).setCellValue((String)data.get("lastitem")); 
						onerow.createCell(8).setCellValue((String)data.get("nextitem")); 
						onerow.createCell(9).setCellValue((String)data.get("chapter")); 
						onerow.createCell(10).setCellValue((String)data.get("pagenumber")); 
						onerow.createCell(11).setCellValue((String)data.get("enterperson")); 
						onerow.createCell(12).setCellValue((String)data.get("enterdate")); 
						onerow.createCell(13).setCellValue((String)data.get("author")); 
						onerow.createCell(14).setCellValue((String)data.get("compile")); 
					    onerow.createCell(15).setCellValue((String)data.get("compileunit")); 
						onerow.createCell(16).setCellValue((String)data.get("publishhouse")); 
						onerow.createCell(17).setCellValue((String)data.get("publishplace")); 
						onerow.createCell(18).setCellValue((String)data.get("publishdate")); 
						onerow.createCell(19).setCellValue((String)data.get("isbn")); 
						onerow.createCell(20).setCellValue((String)data.get("edition")); 
						onerow.createCell(21).setCellValue((String)data.get("wordnumber")); 
						onerow.createCell(22).setCellValue((String)data.get("booksize")); 
						onerow.createCell(23).setCellValue((String)data.get("themewords")); 
						onerow.createCell(24).setCellValue((String)data.get("abstract_")); 
						onerow.createCell(25).setCellValue((String)data.get("classcode")); 
						onerow.createCell(26).setCellValue((String)data.get("dynasty")); 
				 }	
				 String sep = System.getProperty("file.separator");
				 sep = "/";
				 //String tempFilepath = SystemUtil.getWebappRoot().toString();
				// tempFilepath = tempFilepath.replace("\\", "/") + "/temp";
				 String tempFilepath = GlobalParamCache.getInst().getParamByKey("dnmsabfile");
				 System.out.println("tempFilepath::" + tempFilepath );
				 
				 String picFilepath = tempFilepath + sep + "export" ;
				 File picFile = new File(picFilepath);
				 if(!picFile.exists()){
					 picFile.mkdirs();
				 }
				 String destfile = picFilepath + sep + "多囊卵巢古籍题录数据.xls";
				 FileOutputStream fileOut = new FileOutputStream(destfile); 
				 wb.write(fileOut); 
				 fileOut.close();
				
				 //生成图片文件
				 List picList = DBMgr.getDbUtilInst().queryList("select distinct bookname from dnms_book",null);
				 for(int k=0; k<picList.size(); k++){
					 Map onepic = (Map)picList.get(k);
					 String bookname = (String)onepic.get("bookname");
//					 File bookFile = new File(tempFilepath + "/" + bookname);
//					 if(!bookFile.exists()){
//						 bookFile.mkdirs();
//					 }
					 String psql = "select a.id,a.bookname,a.itemno,b.filename,b.filepath from dnms_book a ,dnms_file b where a.id = b.bookid and a.bookname=?";
					 List fileList = DBMgr.getDbUtilInst().queryList(psql,new Object[]{bookname});
					 for(int j=0; j<fileList.size(); j++){
						 Map onefile = (Map)fileList.get(j);
						 String filepath = (String)onefile.get("filepath");
						 String itemno = (String)onefile.get("itemno");
						 String filename = (String)onefile.get("filename");
						 String itemfilePath = picFilepath + sep + bookname + sep + itemno;
						 File itemfile = new File(itemfilePath);
						 if(!itemfile.exists()){
							 itemfile.mkdirs();
						 }
						 File oriFile = new File(tempFilepath + sep + filepath);
						 File newFile = new File(itemfilePath + sep + filename);
						 FileUtil.copyFile(oriFile,newFile);
					 }
				 }
				 ZipfileUtil zipfileUtil = new ZipfileUtil();
				 zipfileUtil.zip(tempFilepath+sep+"古籍数据.zip",picFilepath);
				 message = tempFilepath+sep+"古籍数据.zip";
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		return message;
		
	}
}

